<template>
  <el-dialog :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
      label-width="80px">
      <el-form-item label="用户名" prop="userName">
        <el-input v-model="dataForm.userName" placeholder="用户名"></el-input>
      </el-form-item>
      <el-form-item label="真实姓名" prop="realname">
        <el-input v-model="dataForm.realName" placeholder="真实姓名"></el-input>
      </el-form-item>
      <div>
        <el-form-item label="密码" prop="password" :class="{ 'is-required': !dataForm.id }" v-if="!dataForm.id">
          <el-input v-model="dataForm.password" type="password" placeholder="密码"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="comfirmPassword" :class="{ 'is-required': !dataForm.id }" v-if="!dataForm.id">
          <el-input v-model="dataForm.comfirmPassword" type="password" placeholder="确认密码"></el-input>
        </el-form-item>
      </div>

      <el-form-item label="头像图片" prop="avatar" v-model="dataForm.assetsImg">
        <el-upload style="display: inline-block;margin-left: 10px" :action="url1"
          :headers="{ token: this.$cookie.get('token') }" :show-file-list="false" :on-success="successHandle">
          <img v-if="dataForm.avatar" :src=dataForm.avatar class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>


      <el-form-item label="PDF 文件" prop="files">
        <el-upload
          class="upload-demo"
          :action="url2"
          :on-success="successHandlePDF"
          :before-upload="beforeUploadPDF"
          :file-list="this.dataForm.files"
          multiple
          drag
          accept=".pdf"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将 PDF 文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
<!--        <div class="uploaded-files">-->
<!--          <div v-for="(file, index) in this.dataForm.files" :key="index" class="file-item">-->
<!--            <i class="el-icon-document" @click="previewFile(file)"></i>-->
<!--            <span>{{ file.name }}</span>-->
<!--          </div>-->
<!--        </div>-->
      </el-form-item>


      <el-form-item label="邮箱" prop="email">
        <el-input v-model="dataForm.email" placeholder="邮箱"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="dataForm.mobile" placeholder="手机号"></el-input>
      </el-form-item>
      <el-form-item label="身份证" prop="identities">
        <el-input v-model="dataForm.identities" placeholder="身份证"></el-input>
      </el-form-item>

      <el-form-item label="所属部门" prop="organizationsId">
        <el-select v-model="dataForm.organizationsId" placeholder="请选择所属部门">
          <el-option v-for="item in departmentOptions" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="角色" size="mini" prop="roleIdList">
        <el-checkbox-group v-model="dataForm.roleIdList">
          <el-checkbox v-for="role in roleList" :key="role.roleId" :label="role.roleId">{{ role.roleName
            }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="状态" size="mini" prop="status">
        <el-radio-group v-model="dataForm.status">
          <el-radio :label="0">禁用</el-radio>
          <el-radio :label="1">正常</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { isEmail, isMobile } from '@/utils/validate'

export default {
  data() {
    var validatePassword = (rule, value, callback) => {
      if (!this.dataForm.id && !/\S/.test(value)) {
        callback(new Error('密码不能为空'))
      } else {
        callback()
      }
    }
    var validateComfirmPassword = (rule, value, callback) => {
      if (!this.dataForm.id && !/\S/.test(value)) {
        callback(new Error('确认密码不能为空'))
      } else if (this.dataForm.password !== value) {
        callback(new Error('确认密码与密码输入不一致'))
      } else {
        callback()
      }
    }
    var validateEmail = (rule, value, callback) => {
      if (!isEmail(value)) {
        callback(new Error('邮箱格式错误'))
      } else {
        callback()
      }
    }
    var validateMobile = (rule, value, callback) => {
      if (!isMobile(value)) {
        callback(new Error('手机号格式错误'))
      } else {
        callback()
      }
    }
    // 身份证校验正则表达式
    const idCardReg = /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[0-9Xx]$/;

    // 身份证校验函数
    const validateIdCard = (rule, value, callback) => {
      if (!idCardReg.test(value)) {
        callback(new Error('身份证号码格式错误'));
      } else {
        callback();
      }
    };


    return {
      url1: '',
      url2: '',
      visible: false,
      roleList: [],
      // 添加的部门选项
      departmentOptions: [],
      dataForm: {
        id: 0,
        userName: '',
        realName: '',
        avatar: '',
        password: '',
        comfirmPassword: '',
        salt: '',
        email: '',
        mobile: '',
        roleIdList: [],
        // organizationIdList: [], // 新增部门ID列表
        // department: '',// 新增部门字段
        organizationsId: '', // 新增部门字段·
        status: 1,
        files: [],//合同文件
        identities: ''
      },
      dataRule: {
        identities: [
          { required: true, message: '邮箱不能为空', trigger: 'blur' },
          { validator: validateIdCard, trigger: 'blur' }
        ],
        userName: [
          { required: true, message: '用户名不能为空', trigger: 'blur' }
        ],
        password: [
          { validator: validatePassword, trigger: 'blur' }
        ],
        comfirmPassword: [
          { validator: validateComfirmPassword, trigger: 'blur' }
        ],
        email: [
          { required: true, message: '邮箱不能为空', trigger: 'blur' },
          { validator: validateEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          { validator: validateMobile, trigger: 'blur' }
        ],
        // 添加的部门验证规则
        organizationsId: [
          { required: true, message: '所属部门不能为空', trigger: 'change' }
        ],
        status: [
          { required: true, message: '状态不能为空', trigger: 'change' }
        ]

      }
    }
  },


  methods: {
    init(id) {
      this.url1 = this.$http.adornUrl(`/file/upload4?token=${this.$cookie.get('token')}`)  //头像
      this.url2 = this.$http.adornUrl(`/file/upload5?token=${this.$cookie.get('token')}`)   // pdf合同
      this.dataForm.id = id || 0;

      // 获取角色列表
      this.$http({
        url: this.$http.adornUrl('/sys/role/select'),
        method: 'get',
        params: this.$http.adornParams()
      }).then(({ data }) => {
        this.roleList = data && data.code === 0 ? data.list : [];
      }).then(() => {
        // 获取部门列表
        this.$http({
          url: this.$http.adornUrl('/sys/organizations/list'),
          method: 'get', // 使用GET请求
          data: this.$http.adornData({}) // 传递空数据对象
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.departmentOptions = data.page.list.map(item => ({
              value: item.id,
              label: item.name
            }));
            console.log('organizationsId options:', this.departmentOptions); // 添加调试信息
          } else {
            console.error('Failed to fetch organizationsId list:', data.msg);
          }
        }).catch(error => {
          console.error('Error fetching organizationsId list:', error);
        });
      }).then(() => {
        this.visible = true;
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields();
        });
      }).then(() => {

        if (this.dataForm.id) {
          // 获取用户信息
          this.$http({
            url: this.$http.adornUrl(`/sys/user/info/${this.dataForm.id}`),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.dataForm.userName = data.user.username;
              this.dataForm.avatar = data.user.avatar;
              this.dataForm.salt = data.user.salt;
              this.dataForm.email = data.user.email;
              this.dataForm.mobile = data.user.mobile;
              this.dataForm.roleIdList = data.user.roleIdList;
              this.dataForm.realName = data.user.realName;
              // this.dataForm.organizationIdList = data.user.organizationIdList; // 新增部门ID列表
              // this.dataForm.department = data.user.department; // 新增部门字段
              this.dataForm.status = data.user.status;
              this.dataForm.organizationsId = data.user.organizationsId; // 新增部门字段
              this.dataForm.files =data.user.files,
              this.dataForm.identities =data.user.identities
              console.log(this.dataForm, 'ujik');
            }
          });
        }
      });
    },
    // 检查 PDF 文件类型
    beforeUploadPDF(file) {
      const isPDF = file.type === 'application/pdf';
      if (!isPDF) {
        ElMessage.error('只能上传 PDF 文件');
      }
      return isPDF;
    },
    // 预览文件
    previewFile(file) {
      if (file.url) {
        window.open(file.url, '_blank');
      } else {
        console.log('文件无预览链接');
      }
    },
    // PDF 文件上传成功
    successHandlePDF(response, file, fileList) {
      file.url = response.assetsImg;
      // 确保 this.dataForm.files 是一个数组
      if (!Array.isArray(this.dataForm.files)) {
        this.dataForm.files = [];
      }
      // 将文件信息添加到 dataForm.files 中，建议存储完整的文件对象
      this.dataForm.files.push(file.url);
      console.log('PDF 上传成功', response);
      this.$message.success('PDF 文件上传成功');
    },

    // 图片上传成功
    successHandle(response, file, fileList) {
      console.log(response)
      this.dataForm.avatar =response.assetsImg  // 上传成功后，更新图片路径
      this.$message.success('上传成功')
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // 将 dataForm.files 数组转换为逗号分隔的字符串
          if (Array.isArray(this.dataForm.files) && this.dataForm.files.length > 0) {
            this.dataForm.files = this.dataForm.files.join(',');
          } else {
            this.dataForm.files = ''; // 如果数组为空，设置为空字符串
          }

          this.$http({
            url: this.$http.adornUrl(`/sys/user/${!this.dataForm.id ? 'save' : 'update'}`),
            method: 'post',
            data: this.$http.adornData({
              'userId': this.dataForm.id || undefined,
              'username': this.dataForm.userName,
              'realName': this.dataForm.realName,
              'avatar': this.dataForm.avatar,
              'password': this.dataForm.password,
              'salt': this.dataForm.salt,
              'email': this.dataForm.email,
              'mobile': this.dataForm.mobile,
              'status': this.dataForm.status,
              'roleIdList': this.dataForm.roleIdList,
              // 'organizationIdList': this.dataForm.organizationIdList, // 新增部门ID列表
              'organizationsId': this.dataForm.organizationsId,// 新增部门字段，
              'files':this.dataForm.files,
              'identities':this.dataForm.identities

            })
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.$emit('refreshDataList');
                }
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    }
  }
}
</script>
<style>
.select-box {
  margin-left: 80px;
  margin-bottom: 10px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
